package com.coderknock.bbs.service

import com.coderknock.bbs.mybatis.dao.UserDao
import com.coderknock.bbs.mybatis.domain.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.util.CollectionUtils

/**
 * <p></p>
 * @author 三产
 * @version 1.0
 * @date 2017-12-01
 * @QQGroup 213732117
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
@Service
class UserService(val userDao: UserDao, val passwordEncoder: BCryptPasswordEncoder) : UserDetailsService {

    /**
     * 重载 UserDetailsService 的方法获取用户信息
     * @param email 用户登录时填写的用户名，在本系统中就是邮箱
     */
    override fun loadUserByUsername(email: String): UserDetails {
        val userDetails = userDao.findUserByEmail(email)
        if (userDetails != null) {
            var roleList = userDao.findUserRole(userDetails.id)
            if (!CollectionUtils.isEmpty(roleList)) {
                roleList.forEach { role -> userDetails.addAuthority(role) }
            }
            return userDetails
        }
        throw UsernameNotFoundException("$email 用户不存在！")
    }

    /**
     * 查询所有用户信息（该处只是用于一开始的测试）
     */
    fun findAll() = userDao.findAll()

    /**
     * 根据用户邮箱查询用户信息
     * @param email
     */
    fun findUserByEmail(email: String) = userDao.findUserByEmail(email)

    /**
     * 添加用户
     * @param user
     */
    fun save(user: User): Int {
        //对密码进行加密
        user.passWord = passwordEncoder.encode(user.passWord)
        return userDao.save(user)
    }

    /**
     * 根据用户 id 查询用户的角色
     * @param userId
     */
    fun findUserRole(userId: Int) = userDao.findUserRole(userId)


}